// pages/Lindex/Lindex.js
var template = require('../template/tabber/tabber.js');
var app = getApp(); //引用app.js
var commonURL = app.data.baseURL;
var commonURLYY = app.data.newURL;
var commonURLXX = app.data.lastURL;
var baseURL1 = app.data.baseURL;
var jielong = app.data.jielong;
var jecheck = app.data.jecheck
Page({
  data: {
    imgUrls: [],
    indicatorDots: true,
    swiper: [],
    autoplay: true,
    interval: 5000,
    duration: 300,
    business: {},
    tel: []

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    wx.getStorage({
      key: 'group_tel',
      success: function(res) {
        that.setData({
          group_tel: res.data
        })
      },
    })
    wx.getStorage({
      key: 'supplier_tel',
      success: function(res) {
        that.setData({
          supplier_tel: res.data
        })
      },
    })
    wx.getStorage({
      key: 'join_tel',
      success: function(res) {
        that.setData({
          join_tel: res.data
        })
      },
    })
    template.tabbar("tabBar", 0, this);
    var arr = [];
    wx.request({
      url: 'https://min.lexiangpingou.cn/applet/controller.php?action=getSwiper',
      method: 'POST',
      data: {
        uniacid: app.data.GZHid
      },
      success: function(res) {
        for (var i = 0; i < res.data.data.length; i++) {
          arr.push(res.data.data[i].thumb)
        }
        that.setData({
          swiper: arr
        })
      }
    })
  },
  applyTz: function() {
    wx.navigateTo({
      url: '../apply_grouper/index',
    })
  },
  timeChange: function(timestamp) {
    var arrTimestamp = (timestamp + '').split('');
    for (var start = 0; start < 13; start++) {
      if (!arrTimestamp[start]) {
        arrTimestamp[start] = '0';
      }
    }
    timestamp = arrTimestamp.join('') * 1;

    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - timestamp;

    // 如果本地时间反而小于变量时间
    if (diffValue < 0) {
      return '不久前';
    }

    // 计算差异时间的量级
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;

    // 数值补0方法
    var zero = function(value) {
      if (value < 10) {
        return '0' + value;
      }
      return value;
    };

    // 使用
    if (monthC > 12) {
      // 超过1年，直接显示年月日
      return (function() {
        var date = new Date(timestamp);
        return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
      })();
    } else if (monthC >= 1) {
      return parseInt(monthC) + "月前";
    } else if (weekC >= 1) {
      return parseInt(weekC) + "周前";
    } else if (dayC >= 1) {
      return parseInt(dayC) + "天前";
    } else if (hourC >= 1) {
      return parseInt(hourC) + "小时前";
    } else if (minC >= 1) {
      return parseInt(minC) + "分钟前";
    }
    return '刚刚';

  },
  goPro: function(e) {
    console.log(e)
    var id = e.currentTarget.dataset.id
    wx.setStorage({
      key: 'product',
      data: e.currentTarget.dataset.item,
      success: function() {

      }
    })
    var img = JSON.stringify(e.currentTarget.dataset.img)
    wx.request({
      url: jielong + 'action=addViewCount',
      data: {
        uniacid: app.data.GZHid,
        id: id
      },
      method: 'POST',
      success: function(res) {
        wx.navigateTo({
          url: '../products/products?status=' + e.currentTarget.dataset.status + '&id=' + e.currentTarget.dataset.id + '&img=' + img + '&time=' + e.currentTarget.dataset.time,
        })
      }
    })

  },
  makePhone: function(e) {
    // console.log(e.currentTarget)
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.tel,
    })
  },
  previewImg: function(e) {
    console.log(e)
    wx.previewImage({
      current: e.currentTarget.dataset.src, // 当前显示图片的http链接
      urls: ['e.currentTarget.dataset.src'] // 需要预览的图片http链接列表
    })
  },
  applyseller: function() {
    wx.navigateTo({
      url: '../goods_provide/index',
    })
  },
  gogroup: function() {
    wx.navigateTo({
      url: '../member_list/member_list',
    })
  },
  changeIndicatorDots: function(e) {
    this.setData({
      indicatorDots: !this.data.indicatorDots
    })
  },
  changeAutoplay: function(e) {
    this.setData({
      autoplay: !this.data.autoplay
    })
  },
  intervalChange: function(e) {
    this.setData({
      interval: e.detail.value
    })
  },
  durationChange: function(e) {
    this.setData({
      duration: e.detail.value
    })
  },
  onReady: function() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    wx.showLoading({
      title: '加载中',
    })
    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        wx.request({
          url: jecheck + 'op=isPerson',
          data: {
            uniacid: app.data.GZHid,
            openid: wx.getStorageSync('openid') || app.data.openid
          },
          success: function (res) {
            console.log(res)
            if (res.data.status == 0) {
              wx.showModal({
                title: '提示',
                showCancel: false,
                content: '请完善个人信息',
                complete: function (res) {
                  wx.redirectTo({
                    url: '../setup/index',
                  })
                }
              })
            }
          }
        })
      },
      fail: function (res) {
        wx.redirectTo({
          url: '../../authorization/authorization',
        })
      }
    })
    var that = this;
    this.wxGetUserInfo(app.data.session_key, app.data.openid)
    wx.request({
      url: baseURL1 + 'op=homeinfo',
      success: function(res) {
        console.log(res)
        
        if (res.data.status) {
          if (res.data.data.length > 0) {
            that.setData({
              business: res.data.business,
              homeList: res.data.data,
            })
            if (res.data.business.name.length>0){
              wx.setNavigationBarTitle({ title: res.data.business.name });//设置title文字
            }else{
              wx.setNavigationBarTitle({ title: '火蝶云' });//设置title文字
            }
          }
          let date = Math.floor(Math.round(new Date() / 1000))
          let arr = []
          for (let i = 0; i < res.data.data.length; i++) {
            arr.push(that.timeChange(res.data.data[i].startline))
          }
          that.setData({
            time: arr
          })
          wx.getStorage({
            key: '',
            success: function(res) {},
          })
        }
        wx.hideLoading()
      }
    })
  },
  iscommer: function () {
    wx.request({ //获取是否团长
      url: commonURL + 'op=is_area_commander_copy',
      data: {
        "openid": wx.getStorageSync('openid'),
        "uniacid": app.data.GZHid,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res)
        if (res.data != '') {
          if (res.data.status == 1) {
            wx.setStorage({
              key: 'tzInfo',
              data: res.data.team,
            })
            wx.setStorage({
              key: 'isTz',
              data: 1,
            })
            wx.setStorage({
              key: 'noright',
              data: false,
            })
          } else if (res.data.status == 2) {
            wx.setStorage({
              key: 'isTz',
              data: 0,
            })
            wx.setStorage({
              key: 'noright',
              data: false,
            })
            wx.setStorage({
              key: 'tzInfo',
              data: res.data.team,
            })
          } else {
            wx.setStorage({
              key: 'isTz',
              data: 0,
            })
            wx.setStorage({
              key: 'noright',
              data: true,
            })
            wx.setStorage({
              key: 'tzInfo',
              data: '',
            })
          }
        } else {
          wx.showToast({
            title: '请重新授权',
            icon: 'none'
          })
        }
      }
    })
  },
  getinfo: function (areaid) {
    wx.request({
      url: commonURL + 'op=automatic',
      data: {
        openid: wx.getStorageSync('openid'),
        uniacid: app.data.GZHid,
        areaid: areaid
      },
      success: function (res) {
        console.log('绑定团长' + res)
        console.log(res)
        wx.getStorage({
          key: 'userInfo',
          success: function (res) { },
          fail: function (res) {
            wx.redirectTo({
              url: '../../anthorization/anthorization',
            })
          }
        })
      },
      fail: function (res) {
        wx.getStorage({
          key: 'userInfo',
          success: function (res) { },
          fail: function (res) {
            wx.redirectTo({
              url: '../../anthorization/anthorization',
            })
          }
        })
      }
    })
  },
  wxGetUserInfo(session_key, openid) {
    var that = this;
    wx.getUserInfo({
      success: function (res) {
        // that.globalData.userInfo = res.userInfo;
        typeof cb == "function" && cb(res.userInfo);
        wx.request({
          url: baseURL1 + 'op=check_member',
          data: {
            appid: app.data.appid,
            encryptedData: res.encryptedData,
            iv: res.iv,
            session_key: session_key,
            openid: app.data.openid,
            nickname: res.userInfo.nickName,
            avatar: res.userInfo.avatarUrl,
            gender: res.userInfo.gender,
            province: res.userInfo.province,
            city: res.userInfo.city,
            gender: res.userInfo.gender,
            mid: app.data.mid ? app.data.mid : '',
            xcx: 1
          },
          success: function (res) {
            if (wx.getStorageSync('selectAreaid')) {
              wx.request({
                url: commonURL + 'op=automatic',
                data: {
                  openid: wx.getStorageSync('openid'),
                  uniacid: app.data.GZHid,
                  areaid: wx.getStorageSync('selectAreaid')
                },
                success: function (res) {
                  console.log('绑定团长' + res)
                  console.log(res)
                  that.iscommer()
                },
                fail: function (res) {
                  that.iscommer()
                }
              })
            }else{
              that.iscommer()
            }
            if (res.data.info.unionId) {
              wx.setStorage({
                key: "unionId",
                data: res.data.info.unionId
              })
              that.data.unionId = res.data.info.unionId;
            }
            var data = res.data.member;
            if (data.addmobile && data.addname) {
              wx.setStorage({
                key: "add",
                data: {
                  addmobile: data.addmobile,
                  addname: data.addname
                }
              })
            }
          },
          fail:function(res){
            cosnole.log('入团失败' + res)
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})
